<template>
  <div class="search">
    <n-card :bordered="false" class="mt-4 proCard">
        <n-grid :x-gap="12">
          <n-gi :span="5">
            <div style="background: #fff;padding-left:16px;height: 100%; margin-top: 5px">
              <n-input
                suffix="ios-search"
                v-model:value="searchText"
                placeholder="输入搜索部门"
                clearable
              />
              <div class="tree-bar" :style="{maxHeight: maxHeight,marginTop:'10px'}">
                <n-tree ref="tre" :data="treeData" :pattern="searchText" @update:selected-keys="selectTree"></n-tree>
                <n-spin size="large" fix v-if="treeLoading"></n-spin>
              </div>
            </div>
          </n-gi>
          <n-gi :span="19">
            <n-form
              :model="queryForm"
              ref="queryFormRef"
              label-placement="left"
              inline>
              <n-grid :x-gap="12"  :cols="4" responsive="screen" @keydown.enter.native="handleSearch">
                 <n-gi>
                   <n-form-item label="登陆账号" path="username">
                     <n-input placeholder="请输入登陆账号" v-model:value="queryForm.username" />
                   </n-form-item>
                  </n-gi>
                  <n-gi>
                    <n-form-item label="真实姓名" path="realName">
                      <n-input placeholder="请输入真实姓名" v-model:value="queryForm.realName" />
                    </n-form-item>
                  </n-gi>
                  <n-gi>
                    <n-form-item label="手机号码" path="phone">
                      <n-input placeholder="请输入手机号码" v-model:value="queryForm.phone" />
                    </n-form-item>
                  </n-gi>
                  <n-gi>
                    <n-form-item label="邮箱" path="email">
                      <n-input placeholder="请输入邮箱" v-model:value="queryForm.email" />
                    </n-form-item>
                  </n-gi>
                <n-gi>
                  <n-form-item label="用户状态" path="lockFlag">
                    <n-select placeholder="请选择用户状态" v-model:value="queryForm.lockFlag"  :options="lockList" clearable/>
                  </n-form-item>
                </n-gi>
                <n-gi>
                  <n-form-item style="margin-right: 0" class="br">
                    <n-space>
                      <n-button type="primary" @click="handleSearch">
                        <template #icon>
                          <n-icon>
                            <IosSearch/>
                          </n-icon>
                        </template>查询</n-button>
                      <n-button @click="handleReset">
                        重置</n-button>
                    </n-space>
                  </n-form-item>
                </n-gi>
            </n-grid>
            </n-form>
            <n-grid :x-gap="12" :cols="2" class="operation" style="margin-bottom: 1vh">
              <n-gi>
                <n-space>
                  <n-button type="primary" @click="handleAdd">
                    <template #icon>
                      <n-icon>
                        <IosAdd/>
                      </n-icon>
                    </template>添加</n-button>
                  <n-button type="error" @click="deleteAll">
                    <template #icon>
                      <n-icon>
                        <IosTrash/>
                      </n-icon>
                    </template>
                    删除</n-button>
                </n-space>
              </n-gi>
            </n-grid>
            <n-grid :cols="1" style="margin-bottom: 1vh;">
              <n-gi :span="1">
                <n-alert type="info" size="small">
                  已选择
                  <span class="select-count">{{selectedKeys.length}}</span> 项
                  <a class="select-clear" @click="clearSelect" v-if="selectedKeys.length>0">清空</a>
                </n-alert>
              </n-gi>
            </n-grid>
            <n-grid :cols="1">
              <n-gi>
                <n-data-table
                  ref="table"
                  :columns="column"
                  :pagination="pagination"
                  :loading="loading"
                  :data="data"
                  :row-key="row => row.id"
                  @update:checked-row-keys="handleCheck"
                  @update:page="changePage"
                  @update:page-size="changePageSize"
                  :checked-row-keys="selectedKeys"
                >
                </n-data-table>
              </n-gi>
            </n-grid>
          </n-gi>
        </n-grid>
      <user-form ref="userFormRef" :drawerTitle="drawerTitle" @on-success="handleSuccess"/>
    </n-card>
  </div>
</template>

<script lang="ts">
import {defineComponent,h,ref,onMounted} from 'vue'
import {useMessage,NButton,NTag,useDialog } from 'naive-ui'
import {getDeptTreeData} from '@/api/system/dept'
import {userList,enableUser,disabledUser,deleteUser} from '@/api/system/user'
import {IosSearch,IosAdd,IosTrash} from '@vicons/ionicons4'
import UserForm from "@/views/system/user/UserForm.vue";
export default defineComponent({
  components:{
    IosSearch,
    IosAdd,
    IosTrash,
    NTag,
    UserForm
  },
  name: "User",
  setup(){
    const message=useMessage();
    const dialog=useDialog();
    const searchText=ref('');
    const treeData=ref([]);
    const maxHeight=ref("500px");
    const treeLoading=ref(false);
    const loading=ref(false);
    const data=ref([]);
    const drawerTitle=ref('');
    const userFormRef=ref(null);
    const lockList=ref([
      {
        label:'正常',
        value:0
      },
      {
        label:'锁定',
        value:-1
      },
    ])
    let initQueryForm=()=>{
      return  {
        pageNo:1,
        pageSize:10,
        deptId:null,
      }
    }
    let queryForm=ref(initQueryForm());
    const queryFormRef=ref(null)
    const pagination=ref({
      itemCount:0,
      prefix ({ itemCount }) {
        return `共 ${itemCount} 项`
      },
      page: 1,
      pageSize: 10,
      showSizePicker: true,
      pageSizes: [10, 20,30,40,50],
    })
    const selectedKeys=ref([]);
    const column=ref([
      {
        type: "selection",
        width: 60,
        align: "center",
        fixed: "left"
      },
      {
        type: "index",
        width: 60,
        align: "center",
        fixed: "left"
      },
      {
        title:'账号',
        key:'username',
        minWidth: 60,
        align: 'center',
        sortable: true,
      },
      {
        title: '手机号码',
        align: 'center',
        key: 'phone',
        minWidth: 120
      },
      {
        title: '邮箱',
        align: 'center',
        key: 'email',
        minWidth: 120
      },
      {
        title: '创建时间',
        align: 'center',
        key: 'createTime',
        sortable: true,
        sortType: "desc",
        minWidth: 150
      },
      {
        title: "状态",
        key: "status",
        align: "center",
        width: 110,
        render: (row) => {
          if (row.lockFlag ==0) {
            return h("div", [
              h(NTag,
                {
                  type: 'success',
                },
                { default: () => '启用' }
              )
            ]);
          } else if (row.lockFlag==-1) {
            return h("div", [
              h(NTag,
                {
                  type: 'error',
                },
                { default: () => '禁用' }
              )
            ]);
          }
        }
      },
      {
        title: '操作',
        key: 'actions',
        align:'center',
        render: function (row) {
          let disableButton;
          if (row.lockFlag==0) {
            disableButton = h(
              NButton,
              {
                size: 'small',
                style: {
                  marginRight: "5px"
                },
                onClick: () => disabled(row)
              },
              {default: () => '禁用'}
            )
          } else if(row.lockFlag == -1) {
            disableButton=h(
              NButton,
              {
                type: "success",
                size: "small",
                style: {
                  marginRight: "5px"
                },
                onClick: () => enable(row)
              },
              {default: () => '启用'}
            )
          }
          return h("div", [
            h(
              NButton,
              {
                type: "primary",
                size: "small",
                style: {
                  marginRight: "5px"
                },
                onClick: () => handleEdit(row)
              },
              {default: () => '编辑'}
            ),
            disableButton,
            h(
              NButton,
              {
                type: "error",
                size: "small",
                onClick: () => handleDelete(row)
              },
              {default: () => '删除'}
            )
          ]);
        }
      }
    ])

    function handleDelete(row){
      selectedKeys.value=[];
      selectedKeys.value.push(row.id);
      deleteAll();
    }
    function handleReset() {
      Object.keys(queryForm.value).forEach((key) => {
        queryForm.value[key] = initQueryForm()[key] || null;
      });
      getUserList();
    }
    function deleteAll() {
      if(selectedKeys.value.length<=0){
         message.warning('请选择您要删除的数据');
         return;
      }
      dialog.warning({
        title: '警告',
        content: '你确定要删除所选的'+selectedKeys.value.length+'条数据吗?删除后无法恢复',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick:()=>{
          const ids = selectedKeys.value.join(",");
          deleteUser(ids).then(res=>{
            if(res){
               message.success('删除成功');
               getUserList();
               selectedKeys.value=[]
            }else{
              message.error(res.message)
            }
          })
        },
        onNegativeClick: () => {
        }
      })
    }
    function handleEdit(row) {
      let record={};
      record=Object.assign(record,row);
      userFormRef.value.isShow=true;
      userFormRef.value.userForm=record;
      userFormRef.value.oldUsername=record.username;
      userFormRef.value.oldMobile=record.phone;
      userFormRef.value.userForm.imageList=new Array(record.avatar)
      userFormRef.value.userForm.roleList=record.roleList.map((item)=>item.id);
      drawerTitle.value='修改用户-【'+record.username+'】'
    }
    function handleAdd() {
      userFormRef.value.isShow=true;
      drawerTitle.value='添加用户'
    }
    function handleSuccess(){
      getUserList();
    }
    function clearSelect() {
      selectedKeys.value=[];
    }
    function enable(row) {
      dialog.warning({
        title: '警告',
        content: '你确定要启用用户'+row.username+'?',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
         enableUser(row.id).then(res=>{
           if(res){
              message.success("启用成功");
              getUserList();
           }
         })
        },
        onNegativeClick: () => {
        }
      })
    }
    function disabled(row) {
      dialog.warning({
        title: '警告',
        content: '你确定要禁用用户'+row.username+'?',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
          disabledUser(row.id).then(res=>{
            if(res){
              message.success("禁用成功");
              getUserList();
            }
          })
        },
        onNegativeClick: () => {
        }
      })
    }
    function selectTree(keys){
      if(keys.length>0){
         queryForm.value.deptId=keys[0];
         getUserList();
      }
    }
    function changePageSize(value) {
      queryForm.value.pageSize=value;
      pagination.value.pageSize=value;
      getUserList();
    }
    function changePage(value) {
      queryForm.value.page=value;
      pagination.value.page=value;
      getUserList();
    }
    function handleCheck(keys) {
      selectedKeys.value=keys;
    }
    function getUserList(){
      loading.value=true;
      userList(queryForm.value).then(res=>{
        data.value=res.records;
        pagination.value.itemCount=res.total;
        loading.value=false;
      })
    }
    function handleSearch(){
      getUserList();
    }
    onMounted(async () => {
      treeLoading.value=true;
      let deptTreeData = await getDeptTreeData();
      treeData.value=deptTreeData;
      treeLoading.value=false;
      getUserList();
    })
    return {
      searchText,
      treeData,
      maxHeight,
      treeLoading,
      loading,
      data,
      column,
      pagination,
      queryForm,
      queryFormRef,
      lockList,
      drawerTitle,
      userFormRef,
      selectedKeys,
      selectTree,
      changePageSize,
      changePage,
      handleCheck,
      handleSearch,
      deleteAll,
      handleReset,
      handleAdd,
      handleSuccess,
      clearSelect
    }
  }
})
</script>

<style lang="less" scoped>
@import "../../../styles/Table.less";
</style>
